package com.wocai.jrt.im;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tls.sigcheck.tls_sigcheck;
import com.vteba.utils.common.PropUtils;

public class SigUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(SigUtils.class);
	private static String jniLib = null;
	private static String privateKey = null;
	private static String publicKey = null;
	private static String sdkAppId = null;

	static {
		jniLib = PropUtils.get("im.jniLib");
		privateKey = PropUtils.get("im.privateKey");
		publicKey = PropUtils.get("im.publicKey");
		sdkAppId = PropUtils.get("im.sdkAppId");
    }
	
	/**
	 * @param identifier
	 *            用户标示符，即用户 id
	 *
	 * @return 成功返回 sig,失败返回 null
	 */
	public static String getSig(String identifier) throws Exception {
		String sig = null;

		tls_sigcheck tls_sigcheck = new tls_sigcheck();
		tls_sigcheck.loadJniLib(jniLib);

		File priKeyFile = new File(privateKey);
		StringBuilder strBuilder = new StringBuilder();
		String s = "";

		BufferedReader br = new BufferedReader(new FileReader(priKeyFile));
		while ((s = br.readLine()) != null) {
			strBuilder.append(s + '\n');
		}
		br.close();
		String priKey = strBuilder.toString();
		int ret = tls_sigcheck.tls_gen_signature_ex2(sdkAppId, identifier, priKey);

		if (0 != ret) {
			LOGGER.error("ret " + ret + " " + tls_sigcheck.getErrMsg());
		} else {
			sig = tls_sigcheck.getSig();
		}

		return sig;
	}
	public static void main(String[] args) {
		try {
			System.out.println(getSig("asdfasdf"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
